﻿using Callisto.Controls;
using Dynamics.NAV.Metro.Common;
using Dynamics.NAV.Metro.Controls.Settings;
using Dynamics.NAV.Metro.Data;
using Dynamics.NAV.Metro.Pages;
using Dynamics.NAV.Metro.Pages.ContactPicker;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227

namespace Dynamics.NAV.Metro
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        public const string SETTINGS_CONTAINER = "ConnectionSettings";
        public const string DEFAULT_URL_KEY = "ODataUrl";
        public const string DEFAULT_USERNAME_KEY = "Username";
        public const string DEFAULT_PASSWORD_KEY = "Password";
        public const string DEFAULT_MAX_REC_KEY = "MaxRecords";
        public const string DEFAULT_REC_PER_PAGE_KEY = "RecordsPerPage";
        public const string DEFAULT_URL_VALUE = "http://localhost:7048/DynamicsNAV70/OData/";
        public const string DEFAULT_COMPANY_KEY = "Company";

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();

            //this.Suspending += new SuspendingEventHandler(App_Suspending);

            //ApplicationData.Current.LocalSettings.DeleteContainer(App.SETTINGS_CONTAINER);

            if (!SettingsStorage.LocalSettingsExist(DEFAULT_URL_KEY))
                SettingsStorage.SetLocalSetting(DEFAULT_URL_KEY, DEFAULT_URL_VALUE);
            if (!SettingsStorage.LocalSettingsExist(DEFAULT_USERNAME_KEY))
                SettingsStorage.SetLocalSetting(DEFAULT_USERNAME_KEY, "");
            if (!SettingsStorage.LocalSettingsExist(DEFAULT_PASSWORD_KEY))
                SettingsStorage.SetLocalSetting(DEFAULT_PASSWORD_KEY, "");
            if (!SettingsStorage.LocalSettingsExist(DEFAULT_MAX_REC_KEY))
                SettingsStorage.SetLocalSetting(DEFAULT_MAX_REC_KEY, 1000);
            if (!SettingsStorage.LocalSettingsExist(DEFAULT_REC_PER_PAGE_KEY))
                SettingsStorage.SetLocalSetting(DEFAULT_REC_PER_PAGE_KEY, 20);
            if (!SettingsStorage.LocalSettingsExist(DEFAULT_COMPANY_KEY))
                SettingsStorage.SetLocalSetting(DEFAULT_COMPANY_KEY, "");

            // Create and initialize the application bootstrapper
            AppBootstrapper bootstrapper = new AppBootstrapper();
            bootstrapper.Initialize();
        }

        async void App_Suspending(object sender, SuspendingEventArgs e)
        {
            SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
            // save state to session
            await LocalStorage.Save();
            deferral.Complete();
        }

        async protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            base.OnLaunched(args);
            
            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                // restore last session
                await LocalStorage.Restore();
            }
        }

        protected override void OnWindowCreated(WindowCreatedEventArgs args)
        {
            SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;
            
            base.OnWindowCreated(args);
        }

        void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            SettingsCommand cmd = new SettingsCommand("Settings", "Connection", (x) =>
            {
                SettingsFlyout settings = new SettingsFlyout();
                settings.HeaderText = "Connection";
                //settings.Background = new SolidColorBrush(Colors.Red);
                settings.Closed += settings_Closed;
                settings.Content = new ConnectionSettingsControl();
                settings.IsOpen = true;
            });

            args.Request.ApplicationCommands.Add(cmd);
        }

        async void settings_Closed(object sender, object e)
        {
            // save state to session
            await LocalStorage.Save();
        }

        protected override void OnActivated(IActivatedEventArgs args)
        {
            if (args.Kind == ActivationKind.ContactPicker)
            {
                var view = new ContactPickerPage();
                var vm = new ContactPickerViewModel((ContactPickerActivatedEventArgs)args);

                view.DataContext = vm;

                Window.Current.Content = view;
                Window.Current.Activate();
            }
            else
            {
                base.OnActivated(args);
            }
        }
    }
}
